package com.meida.module.bus.provider.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.DateUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.enums.OrderStateYEnum;
import com.meida.module.bus.client.enums.RedisKeyEnum;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.live.handler.RoomInitHandler;
import com.meida.module.live.io.agora.utils.RtmTokenBuilderUtil;
import com.meida.module.system.provider.service.SysExpireStrategyService;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

@Component
@AllArgsConstructor
public class OrderRoomInitHandler implements RoomInitHandler {

    private final BusOrderService orderService;
    private final RtmTokenBuilderUtil rtmTokenBuilderUtil;

    private final AppUserService userService;

    private final SysExpireStrategyService sysExpireStrategyService;

    @Override
    public EntityMap initRoomInfo(String roomId, String userType, Long userId) {
        EntityMap data = new EntityMap();
        ApiAssert.isNotEmpty("userType不能为空", userType);
        ApiAssert.isNotEmpty("userId不能为空", userId);
        ApiAssert.isNotEmpty("roomId不能为空", roomId);
        String userName = "";
        if (userType.equals("APP")) {
            AppUser appUser = userService.getUserById(userId);
            ApiAssert.isNotEmpty("用户不存在", appUser);
            userName = FlymeUtils.getString(appUser.getNickName(),"未知");
        } else {
            userName = "管理员";
        }
        BusOrder busOrder = orderService.getById(roomId);
        ApiAssert.isNotEmpty("订单不存在", busOrder);
        //学霸id
        Long answerUserId = busOrder.getAnswerUserId();
        String rtmToken = rtmTokenBuilderUtil.getRtmToken(String.valueOf(userId), 3600 * 24);
        //默认学生
        Integer roleType = 2;
        if (userId.equals(answerUserId)) {
            roleType = 1;
            orderService.updateOrderState(Long.parseLong(roomId), OrderStateYEnum.OrderState3.getValue());
        }

        data.put("roomId", roomId);
        data.put("rtmToken", rtmToken);
        data.put("userId", userId);
        data.put("userName", userName);
        data.put("roomType", 4);
        data.put("roleType", roleType);
        data.put("language", "zh");
        data.put("region", "CN");
        data.put("duration", 30 * 60);
        data.put("roomName", "预约辅导直播间");
        data.put("pretest", true);
        return data;
    }
}
